package net.k3rnel.abugadro.gcodes;

import net.k3rnel.abugadro.R;
import net.k3rnel.abugadro.providers.ExternalContentProvider;
import net.k3rnel.abugadro.providers.Project.Projects;
import net.k3rnel.abugadro.util.NotifyingAsyncQueryHandler;
import net.k3rnel.abugadro.util.UIUtils;
import net.k3rnel.abugadro.util.NotifyingAsyncQueryHandler.AsyncQueryListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.BaseColumns;
import android.view.View;
import android.widget.TextView;

public class GoogleCodeHome extends Activity implements AsyncQueryListener{

	private NotifyingAsyncQueryHandler mHandler;
	private int projectId;
	private String projName;
	private volatile SyncThread mSyncThread;
	private boolean mSync = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gcode_home);

		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);

		final Uri projectUri = getIntent().getData();
		mHandler.startQuery(projectUri, ProjectsQuery.PROJECTION);
	}

	@Override
	public boolean moveTaskToBack(boolean nonRoot) {
		stopThread();
		return super.moveTaskToBack(nonRoot);
	}
	
	/** {@inheritDoc} */
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		try {
			if (!cursor.moveToFirst()) return;

			// Load current project content for editing
			projectId = cursor.getInt(ProjectsQuery.ID);
			projName = cursor.getString(ProjectsQuery.NAME);
			((TextView) findViewById(R.id.title_text)).setText(projName);

		} finally {
			cursor.close();
		}

	}

	public synchronized void startThread(){
		if(mSyncThread == null){
			mSyncThread = new SyncThread(handler);
			mSyncThread.start();
		}
	}
	public synchronized void stopThread(){
		if(mSyncThread != null){
			Thread moribund = mSyncThread;
			mSyncThread = null;
			moribund.interrupt();
		}
	}

	/** Handle "refresh" title-bar action. */
	public void onRefreshClick(View v) {
		if(!mSync)
			startThread();
	}
	/** Handle "search" title-bar action. */
	public void onSearchClick(View v) {
//		UIUtils.goSearch(this);
		AlertDialog ad = new AlertDialog.Builder(this)
		.setPositiveButton("Okay", null)
		.setTitle("Sorry Dude!")
		.setMessage("Search function isn't ready!")
		.create();
		ad.show();
	}

	/** Handle "home" title-bar action. */
	public void onHomeClick(View v) {
		UIUtils.goHome(this);
	}

	/** Handle "open" title-bar action. */
	public void onOpenClick(View v) {
		final Uri issuesURI = Uri.parse("content://"+ ExternalContentProvider.AUTHORITY + "/projects/"+projectId+"/issues/");
		Intent i = new Intent(getApplicationContext(),IssuesList.class);
		i.setAction("net.k3rnel.abugadro.OPEN");
		i.setDataAndType(issuesURI, "vnd.android.cursor.dir/*");
		i.putExtra(Intent.EXTRA_TITLE,projName);
		i.putExtra("projId",projectId);
		startActivity(i);
	}
	/** Handle "closed" title-bar action. */
	public void onClosedClick(View v) {
		final Uri issuesURI = Uri.parse("content://"+ ExternalContentProvider.AUTHORITY + "/projects/"+projectId+"/issues/");
		Intent i = new Intent(getApplicationContext(),IssuesList.class);
		i.setAction("net.k3rnel.abugadro.CLOSED");
		i.setDataAndType(issuesURI, "vnd.android.cursor.dir/*");
		i.putExtra(Intent.EXTRA_TITLE,projName);
		i.putExtra("projId",projectId);
		startActivity(i);
	}
	/** Handle "commits" title-bar action. */
	public void onCommitsClick(View v) {
		AlertDialog ad = new AlertDialog.Builder(this)
		.setPositiveButton("Okay", null)
		.setTitle("Hold it!")
		.setMessage("Commit function isn't ready yet!")
		.create();
		ad.show();
	}
	/** Handle "wiki" title-bar action. */
	public void onWikiClick(View v) {
		AlertDialog ad = new AlertDialog.Builder(this)
		.setPositiveButton("Okay", null)
		.setTitle("Hold it!")
		.setMessage("Wiki function isn't ready yet!")
		.create();
		ad.show();
	}

	private void updateRefreshStatus() {
		findViewById(R.id.gcode_home_btn_refresh).setVisibility(
				mSync ? View.GONE : View.VISIBLE);
		findViewById(R.id.gcode_home_btn_refresh_progress).setVisibility(
				mSync ? View.VISIBLE : View.GONE);
	}

	/** {@link Projects} query parameters. */
	private interface ProjectsQuery {
		String[] PROJECTION = {
				BaseColumns._ID,
				Projects.NAME,
		};
		int ID = 0;
		int NAME = 1;
	}
	
	 final Handler handler = new Handler() {
	        public void handleMessage(Message msg) {
	                updateRefreshStatus();
	        }
	    };

	/** Nested class that performs progress calculations (counting) */
	public class SyncThread extends Thread {
		Handler mHandler;

		SyncThread(Handler h) {
	            mHandler = h;
	        }

		public void run() {  
			mSync = true;
			mHandler.sendMessage(new Message());
			new SaxFeedParser(getContentResolver(),"http://code.google.com/feeds/issues/p/"+projName+"/issues/full?max-results=1400",projectId,0,0).parse();
			mSync = false;
			mHandler.sendMessage(new Message());
			stopThread();
		}
	}
}